import { ref, onUnmounted } from 'vue'
import { showSuccessToast, type FormInstance } from 'vant'
import 'vant/es/toast/style'
import { sendMobileCode } from '@/api/user'

export function useSendCode(mobile: string) {
  const isPass = ref(true) //true密码登录 | false短信登录
  const code = ref('') //验证码
  const time = ref(0)
  const form = ref<FormInstance>() //获取表单实例
  let timeId: number //倒计时定时器ID
  const send = async () => {
    if (time.value > 0) return
    try {
      //输入手机号时,对手机号进行校验
      await form.value?.validate('mobile')
      const { data } = await sendMobileCode(mobile, 'login')
      showSuccessToast('发送成功')
      //填入验证码
      code.value = data.code
      //倒计时开始
      time.value = 60
      timeId = window.setInterval(() => {
        time.value--
        if (time.value <= 0) window.clearInterval(timeId)
      }, 1000)
    } catch (error) {
      console.log(error)
    }
  }

  onUnmounted(() => {
    window.clearInterval(timeId)
  })

  return {
    isPass,
    code,
    time,
    form,
    send,
  }
}
